import { CaretLeftOutlined, CaretRightOutlined } from '@ant-design/icons'
import { App, AutoComplete, Col, DatePicker, Form, Input, message, Radio, Row, Select } from 'antd'
import dayjs from 'dayjs'
import Image from 'next/image'
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react'

import { Entity, EnumsRes, Violation } from '@/api/interface'
import { EntityEnums, OtherEntityEnums, UploadFile } from '@/api/modules'
import add from '@/assets/images/add.png'
import arrowNext from '@/assets/images/arrow-next.png'
import arrowPre from '@/assets/images/arrow-pre.png'
import close from '@/assets/images/close.png'
import del from '@/assets/images/delete.png'
import file from '@/assets/images/file.png'
import light from '@/assets/images/light.png'
import useLocale from '@/utils/useLocale'

import locale from '../locale'
import styles from '../styles/index.module.less'

const { TextArea } = Input

const fileTypes = [
  'image/pjpeg',
  'image/jpeg',
  'image/png',
  'application/msword',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  'application/vnd.ms-excel',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  'application/pdf',
]

interface FileUploadComponentProps {
  value?: any[]
  onChange?: (_: any[]) => void
}

const FileUploadComponent = ({ onChange }: FileUploadComponentProps) => {
  const t = useLocale(locale)
  const [fileList, setFileList] = useState<any[]>([])
  const fileInputRef = useRef<HTMLInputElement | null>(null)
  const handleFileSelect = () => {
    if (fileList?.length! >= 10)
      return message.warning(t['form.complaint.attachments.upload.length.error'])
    if (fileInputRef.current) {
      fileInputRef.current.value = ''
      fileInputRef.current.click()
    }
  }

  const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files
    if (files!.length > 5)
      return message.warning(t['form.complaint.attachments.upload.length.warning'])

    const totalFiles = fileList?.length || 0
    const remainingSlots = 10 - totalFiles
    if (!files) return
    if (files.length > remainingSlots)
      return message.warning(t['form.complaint.attachments.upload.length.error'])

    const uploadPromises = Array.from(files).map(async (file) => {
      const imgType = fileTypes.includes(file.type)
      const imgSize = file.size / 1024 / 1024 < 200
      if (!imgType) {
        message.warning(t['form.complaint.attachments.upload.type.warning'])
        return null
      }
      if (!imgSize) {
        message.warning(t['form.complaint.attachments.upload.size.warning'])
        return null
      }

      const excelFormData = new FormData()
      excelFormData.append('file', file)
      const { data } = await UploadFile(excelFormData)
      return { desc: '', href: data, id: '' }
    })

    const uploadedFiles = await Promise.all(uploadPromises)

    // Filter out null values (warnings) and update the state with uploaded files
    const filteredFiles = uploadedFiles.filter(
      (file) => file !== null
    ) as Violation['supportEntities']

    setFileList([...fileList, ...filteredFiles])
  }

  const delFile = (file: string) => {
    const files = fileList.filter((item) => item.href !== file)
    setFileList([...files])
  }
  const triggerChange = (changedValue: any[]) => {
    onChange?.(changedValue)
  }
  useEffect(() => {
    triggerChange(fileList)
  }, [fileList])

  return (
    <>
      {fileList?.length ? (
        <div className={styles['form-complaint-file']}>
          {fileList?.map((item) => {
            return (
              <div className={styles['form-complaint-file-item']} key={item.href}>
                <Image src={file} className={styles['file-icon']} alt="file" />
                <span className={styles['file-text']}>{item.href}</span>
                <Image
                  onClick={() => delFile(item.href)}
                  src={close}
                  className={styles['file-close']}
                  alt="close"
                />
              </div>
            )
          })}
        </div>
      ) : (
        <div className="mb-3"></div>
      )}

      <div className={styles['form-button-upload']} onClick={handleFileSelect}>
        <Image src={add} className={styles['button-icon']} alt="upload" />
        <span className={styles['button-text']}>{t['form.complaint.attachments.upload']}</span>
        <input
          type="file"
          multiple
          style={{ display: 'none' }}
          ref={fileInputRef}
          onChange={handleFileUpload}
          accept=".jpeg,.png,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.pdf"
        />
      </div>
    </>
  )
}

interface Props {
  t: any
  lang: string
  enums: { [key: string]: EnumsRes[] }
  setSetup: Dispatch<SetStateAction<number>>
  violation: Partial<Violation>
  setViolation: Dispatch<SetStateAction<Partial<Violation>>>
}

export default function ComplaintDetails({
  t,
  lang,
  enums,
  setSetup,
  violation,
  setViolation,
}: Props) {
  const [form] = Form.useForm()

  const { message } = App.useApp()

  const [report, setReport] = useState<boolean>()

  useEffect(() => {
    if (violation.emirate) changeEmirate(violation.emirate)
    form.setFieldsValue(violation)
    setReport(violation.hasReported)
    getOtherEntity()
  }, [])

  const [entityEnums, setEntityEnums] = useState<Partial<Entity>[]>([])
  const changeEmirate = async (value: EnumsRes['key']) => {
    form.setFieldsValue({
      emirateEntity: undefined,
      emirateEntityOther: '',
    })
    if (!value) {
      setViolation({ ...violation, emirate: undefined, emirateEntity: undefined })
      setEntityEnums([])
    } else {
      setViolation({ ...violation, emirate: value, emirateEntity: undefined })
      const { data } = await EntityEnums({ emirate: value })
      const other = {
        id: -1,
        name: 'Other - Authority',
        nameAr: 'أخرى - السلطة',
      }
      setEntityEnums(() => [...data, other])
    }
  }

  const [otherEntity, setOtherEntity] = useState<string[]>([])
  const [otherEntityOptions, setOtherEntityOptions] = useState<string[]>([])
  const getOtherEntity = async () => {
    const { data } = await OtherEntityEnums()
    setOtherEntity(data)
    // setOtherEntityOptions(data)
  }

  const getPanelValue = (searchText: string) => {
    return !searchText
      ? []
      : otherEntity.filter((item) => item.toLowerCase().includes(searchText.toLowerCase()))
  }

  const focusEntity = () => {
    if (!violation.emirate) return message.warning(t['form.complaint.emirate.warning'])
  }

  const onFinish = (values: Partial<Violation>) => {
    if (!(isuploadAttachments && values.supportEntities && values.supportEntities.length > 0)) {
      setvalidatorAttachments(true)
    }
    const entity = entityEnums.find((item) => item.id === values.emirateEntity)
    setViolation({
      ...violation,
      ...values,
      violationDate: dayjs(violation.violationDateValue).format('DD/MM/YYYY'),
      refYear: dayjs(values.complaintDateValue).format('DD/MM/YYYY'),
      // refMonth: dayjs(values.complaintDateValue).format('DD/MM/YYYY'),
      // refYear: dayjs(values.complaintDateValue).format('YYYY'),
      // refMonth: dayjs(values.complaintDateValue).format('MM'),
      emirateEntityName: entity ? entity[lang === 'en-US' ? 'name' : 'nameAr'] : '--',
    })
    setSetup(4)
  }

  const FormLabel = ({
    title,
    required = true,
    small = false,
  }: {
    title: string
    required?: boolean
    small?: boolean
  }) => {
    return (
      <span className={small ? styles['form-item-label-small'] : styles['form-item-label']}>
        {title}
        {required && <span className={styles['form-item-label-required']}>*</span>}
      </span>
    )
  }

  const disabledDate = (current: any) => {
    return current && current > dayjs().endOf('day')
  }

  const [isuploadAttachments, setIsuploadAttachments] = useState<boolean>(true)
  const [validatorAttachments, setvalidatorAttachments] = useState<boolean>(true)

  useEffect(() => {
    if (isuploadAttachments) {
      setTimeout(() => {
        setvalidatorAttachments(true)
      }, 300)
    } else {
      setvalidatorAttachments(false)
    }
  }, [isuploadAttachments])
  // const checkSupportEntities = (_: any, value: any[]) => {
  //   console.log(value)
  //   if (value.length > 0) {
  //     return Promise.resolve()
  //   }
  //   return Promise.reject(new Error(t['form.complaint.attachments.mssage']))
  // }

  return (
    <div className={styles['form-complaint']}>
      <h2 className={styles['form-title-h2']}>{t['form.complaint.title']}</h2>
      <div className={styles['form-alert']}>
        <Image src={light} className={styles['alert-icon']} alt="light" />
        <span className={styles['alert-text']}>{t['form.complaint.alert']}</span>
      </div>
      <Form
        layout="vertical"
        onValuesChange={(_: Partial<Violation>, values: Partial<Violation>) => {
          console.log(values)
        }}
        name="complaint"
        form={form}
        onFinish={onFinish}
      >
        <Row gutter={24}>
          <Col md={12} xs={24}>
            <Form.Item label={<FormLabel title={t['form.complaint.emirate']} />}>
              <Form.Item
                name="emirate"
                rules={[{ required: true, message: t['form.complaint.emirate.error'] }]}
              >
                <Select
                  options={enums.Emirate.map((item) => ({
                    value: item?.key,
                    label: item?.value[lang === 'en-US' ? 'en' : 'ar'],
                  }))}
                  onChange={changeEmirate}
                  allowClear
                  showSearch
                  optionFilterProp="label"
                  placeholder={t['form.complaint.placeholder.emirate']}
                  suffixIcon={lang === 'en-US' ? <CaretRightOutlined /> : <CaretLeftOutlined />}
                />
              </Form.Item>
            </Form.Item>
          </Col>
          <Col md={12} xs={24}>
            <Form.Item label={<FormLabel title={t['form.complaint.entityName']} />}>
              <Form.Item
                name="emirateEntity"
                rules={[{ required: true, message: t['form.complaint.entityName.error'] }]}
              >
                <Select
                  options={entityEnums.map((item) => ({
                    value: item?.id,
                    label: item[lang === 'en-US' ? 'name' : 'nameAr'],
                  }))}
                  onFocus={focusEntity}
                  onChange={(value) => setViolation({ ...violation, emirateEntity: value })}
                  allowClear
                  showSearch
                  optionFilterProp="label"
                  placeholder={t['form.complaint.placeholder.entityName']}
                  suffixIcon={lang === 'en-US' ? <CaretRightOutlined /> : <CaretLeftOutlined />}
                />
              </Form.Item>
            </Form.Item>
          </Col>
          {violation.emirateEntity === -1 && (
            <Col xs={24}>
              <Form.Item label={<FormLabel title={t['form.complaint.entityOtherName']} />}>
                <Form.Item
                  name="emirateEntityOther"
                  rules={[{ required: true, message: t['form.complaint.entityOtherName.error'] }]}
                >
                  {/* <Input maxLength={200} placeholder={'Enter The Entity Other Name'} /> */}
                  <AutoComplete
                    options={otherEntityOptions.map((item) => ({
                      value: item,
                    }))}
                    onSearch={(text) => setOtherEntityOptions(getPanelValue(text))}
                    allowClear
                    placeholder={t['form.complaint.placeholder.entityOtherName']}
                    maxLength={100}
                  />
                </Form.Item>
              </Form.Item>
            </Col>
          )}
          <Col span={24}>
            <Form.Item label={<FormLabel title={t['form.complaint.type']} />}>
              <Form.Item
                name="violationType"
                rules={[{ required: true, message: t['form.complaint.type.error'] }]}
              >
                <Select
                  options={enums.ViolationType.map((item) => ({
                    value: item?.key,
                    label: item?.value[lang === 'en-US' ? 'en' : 'ar'],
                  }))}
                  allowClear
                  showSearch
                  optionFilterProp="label"
                  placeholder={t['form.complaint.placeholder.type']}
                  suffixIcon={lang === 'en-US' ? <CaretRightOutlined /> : <CaretLeftOutlined />}
                />
              </Form.Item>
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item label={<FormLabel title={t['form.complaint.reported']} />}>
              <Form.Item
                name="hasReported"
                rules={[{ required: true, message: t['form.complaint.reported.error'] }]}
              >
                <Radio.Group
                  size="large"
                  onChange={(e) => {
                    setReport(e.target.value)
                  }}
                >
                  <Radio value={true}> {t['form.complaint.reported.radio.yes']} </Radio>
                  <Radio value={false}> {t['form.complaint.reported.radio.no']} </Radio>
                </Radio.Group>
              </Form.Item>
            </Form.Item>
          </Col>
          {report ? (
            <>
              <Col xs={24}>
                <Form.Item label={<FormLabel title={t['form.complaint.entityName']} />}>
                  <Form.Item
                    name="refEntity"
                    rules={[{ required: true, message: t['form.complaint.entityName.error'] }]}
                  >
                    <Input maxLength={100} placeholder={t['form.complaint.entityName']} />
                  </Form.Item>
                </Form.Item>
              </Col>
              <Col md={12} xs={24}>
                <Form.Item
                  label={
                    <FormLabel
                      title={`${t['form.complaint.reference']} ${t['form.complaint.any']}`}
                      required={false}
                    />
                  }
                >
                  <Form.Item name="refRefNumber">
                    <Input maxLength={200} placeholder={t['form.complaint.reference']} />
                  </Form.Item>
                </Form.Item>
              </Col>
              <Col md={12} xs={24}>
                <Form.Item
                  label={
                    <FormLabel
                      title={`${t['form.complaint.complaintDate']} ${t['form.complaint.any']}`}
                      required={false}
                    />
                  }
                >
                  <Form.Item name="complaintDateValue">
                    <DatePicker
                      disabledDate={disabledDate}
                      // picker="month"
                      format={'DD/MM/YYYY'}
                      style={{ width: '100%' }}
                    />
                  </Form.Item>
                </Form.Item>
              </Col>
              <div
                className={styles['form-complaint-line']}
                style={
                  lang === 'en-US'
                    ? { transform: 'translateX(1.5%)' }
                    : { transform: 'translateX(-1.5%)' }
                }
              />
            </>
          ) : (
            <></>
          )}
          <Col span={24}>
            <Form.Item
              label={<FormLabel title={t['form.complaint.violationDate']} required={false} />}
            >
              <span className={styles['form-title-extra']} style={{ marginBottom: '10px' }}>
                {t['form.complaint.violationDate.extra']}
              </span>
              <Form.Item name="violationDateValue">
                <DatePicker disabledDate={disabledDate} format={'DD/MM/YYYY'} />
              </Form.Item>
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item label={<FormLabel title={t['form.complaint.description']} />}>
              <span className={styles['form-title-extra']} style={{ marginBottom: '10px' }}>
                {t['form.complaint.description.extra']}
              </span>
              <Form.Item
                name="violationDesc"
                rules={[
                  { required: true, min: 20, message: t['form.complaint.description.error'] },
                ]}
              >
                <TextArea
                  rows={4}
                  showCount
                  maxLength={5000}
                  placeholder={t['form.complaint.placeholder.description']}
                />
              </Form.Item>
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item
              label={<FormLabel title={t['form.complaint.additional']} required={false} />}
            >
              <Form.Item name="violationAdditionalDetails">
                <TextArea
                  rows={4}
                  showCount
                  maxLength={5000}
                  placeholder={t['form.complaint.placeholder.additional']}
                />
              </Form.Item>
            </Form.Item>
          </Col>
          <Col span={24} className={styles['form-complaint-witnesses']}>
            <Form.Item label={<FormLabel title={t['form.complaint.witnesses']} required={false} />}>
              <Form.List name="violators">
                {(fields, { add, remove }) => (
                  <>
                    {fields.map(({ key, name, ...restField }) => (
                      <div key={key} className={styles['form-complaint-witnesses-list']}>
                        <Form.Item
                          label={
                            <FormLabel title={t['form.complaint.witnesses.name']} small={true} />
                          }
                        >
                          <Form.Item
                            {...restField}
                            name={[name, 'concernedParties']}
                            rules={[
                              { required: true, message: t['form.complaint.witnesses.name.error'] },
                            ]}
                          >
                            <Input
                              maxLength={200}
                              placeholder={t['form.complaint.witnesses.placeholder.input']}
                            />
                          </Form.Item>
                        </Form.Item>
                        <Form.Item
                          label={
                            <FormLabel title={t['form.complaint.witnesses.role']} small={true} />
                          }
                        >
                          <Form.Item
                            {...restField}
                            name={[name, 'role']}
                            rules={[
                              { required: true, message: t['form.complaint.witnesses.role.error'] },
                            ]}
                          >
                            <Select
                              options={enums.ViolatorOrWitness.map((item) => ({
                                value: item.key,
                                label: item.value[lang === 'en-US' ? 'en' : 'ar'],
                              }))}
                              allowClear
                              showSearch
                              optionFilterProp="label"
                              placeholder={t['form.complaint.witnesses.placeholder.select']}
                              suffixIcon={
                                lang === 'en-US' ? <CaretRightOutlined /> : <CaretLeftOutlined />
                              }
                            />
                          </Form.Item>
                        </Form.Item>
                        <Form.Item
                          label={
                            <FormLabel
                              title={t['form.complaint.witnesses.nationality']}
                              small={true}
                            />
                          }
                        >
                          <Form.Item
                            {...restField}
                            name={[name, 'nationality']}
                            rules={[
                              {
                                required: true,
                                message: t['form.complaint.witnesses.nationality.error'],
                              },
                            ]}
                          >
                            <Select
                              options={enums.Nationality.map((item) => ({
                                value: item.key,
                                label: item.value[lang === 'en-US' ? 'en' : 'ar'],
                              }))}
                              allowClear
                              showSearch
                              optionFilterProp="label"
                              placeholder={t['form.complaint.witnesses.placeholder.select']}
                              suffixIcon={
                                lang === 'en-US' ? <CaretRightOutlined /> : <CaretLeftOutlined />
                              }
                            />
                          </Form.Item>
                        </Form.Item>
                        {/* del */}
                        <Image
                          onClick={() => remove(name)}
                          src={del}
                          className={styles['form-complaint-witnesses-del']}
                          alt="del"
                        />
                        {/* h5-del */}
                        <div
                          className={styles['form-complaint-witnesses-del-h5']}
                          onClick={() => remove(name)}
                        >
                          <span>Delete</span>
                        </div>
                        {/* line */}
                        <div
                          className={styles['form-witnesses-line']}
                          style={
                            lang === 'en-US'
                              ? { transform: 'translateX(1.5%)' }
                              : { transform: 'translateX(-1.5%)' }
                          }
                        />
                      </div>
                    ))}
                    <span onClick={() => add()} className={styles['form-complaint-witnesses-add']}>
                      {t['form.complaint.witnesses.add']}
                    </span>
                  </>
                )}
              </Form.List>
            </Form.Item>
          </Col>
          <Col span={24} className="!mb-5">
            <Form.Item
              label={
                <FormLabel title={t['form.complaint.attachments.quesetion']} required={false} />
              }
            >
              <Radio.Group
                size="large"
                value={isuploadAttachments}
                onChange={(e) => {
                  setIsuploadAttachments(e.target.value)
                }}
              >
                <Radio value={true}> {t['form.complaint.reported.radio.yes']} </Radio>
                <Radio value={false}> {t['form.complaint.reported.radio.no']} </Radio>
              </Radio.Group>
            </Form.Item>
          </Col>
          {isuploadAttachments && (
            <>
              <Col span={24}>
                <Form.Item label={<FormLabel title={t['form.complaint.attachments']} />}>
                  <span className={styles['form-title-extra']} style={{ marginBottom: '10px' }}>
                    {t['form.complaint.attachments.extra']}
                  </span>
                  <Form.Item
                    name="supportEntities"
                    rules={[
                      {
                        required: validatorAttachments,
                        message: t['form.complaint.attachments.mssage'],
                      },
                    ]}
                  >
                    <FileUploadComponent />
                  </Form.Item>
                </Form.Item>
              </Col>
            </>
          )}
        </Row>
        <div className={styles['form-button']}>
          <div className={styles['form-button-pre']} onClick={() => setSetup(2)}>
            <Image src={arrowPre} className={styles['button-icon']} alt="pre" />
            <span className={styles['button-text']}>{t['form.button.previous']}</span>
          </div>
          <div className={styles['form-button-next']} onClick={() => form.submit()}>
            <span className={styles['button-text']}>{t['form.button.next']}</span>
            <Image src={arrowNext} className={styles['button-icon']} alt="next" />
          </div>
        </div>
      </Form>
    </div>
  )
}
